<template>
	<div class="container">
		<div class="mb15 my-w-e-toolbar">
			<div class="mb15 my-w-e-toolbar">
				<el-button  type="default" class="ml10" @click="onOpenAddMenu">
					新增配置
				</el-button>
				<el-button   type="default" class="ml10" @click="onOpenEditMenu" :disabled="SelectID==='0'" >			 
					修改配置
				</el-button>
				<!--
				<el-button size="small" type="default" class="ml10" @click="onOpenMenuURI">
					关联URI
				</el-button>
				-->
				<el-button   type="default" class="ml10" @click="openDEL" :disabled="SelectID==='0'" >			 		 
					删除配置
				</el-button>
				<el-button   type="default" class="ml10" @click="CopyID" :disabled="SelectID==='0'" v-if="1==2" >			 
					复制ID
				</el-button>
			</div>
		</div>
		<el-row :gutter="20">
			<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="margin-bottom: 20px">
				<div class="tree-body">
					<Ztree ref="ZtreeRef" />
				</div>
			</el-col>
		</el-row>

		<el-dialog
			:title="ruleForm.ID > 0 ? '修改配置' : '创建配置'"
			v-model="isShowDialog"
			width="700px"
			:close-on-click-modal="false"
			:close-on-press-escape="false"
		>
			<el-form :model="ruleForm"  label-width="120px" ref="userForm">
				<el-row :gutter="35">
					<el-input v-model="ruleForm.ID" type="hidden"></el-input>
					<el-input v-model="ruleForm.ParentID" type="hidden"></el-input>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item
							label="KEY"
							:rules="[
								{ required: true, message: '必须有KEY' },
								{ validator: validateKey, trigger: 'blur' },
							]"
							prop="Key"
						>
							<el-input v-model="ruleForm.Key" placeholder="Key" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="名称" :rules="[{ required: true, message: '请填写名称' }]" prop="Text">
							<el-input v-model="ruleForm.Text" placeholder="名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="说明" prop="Description">
							<el-input type="textarea" v-model="ruleForm.Description" rows="2" placeholder="说明" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="表单类型" prop="Type">
						  <el-select v-model="ruleForm.Type" clearable>
						    <el-option v-for="(item, index) in TypeOptions" :key="index" :label="item.label"
						      :value="item.value"></el-option>
						  </el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="富文本编辑器" prop="Html">
							<el-switch v-model="ruleForm.Html" active-text="是" inactive-text="否" active-value="1" inactive-value="0" class="ml-2" style="--el-switch-on-color: #13ce66;" :disabled="ruleForm.Type!='text' && ruleForm.Type!='textarea'"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="选项表达式" prop="Options">
							<el-input type="textarea" v-model="ruleForm.Options" rows="2" placeholder="选项表达式" clearable :disabled="ruleForm.Type!='radio' && ruleForm.Type!='checkbox' && ruleForm.Type!='select'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="最大值" prop="Max">
							<el-input v-model="ruleForm.Max" placeholder="最大值" clearable :disabled="ruleForm.Type!='date' && ruleForm.Type!='number'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="最小值" prop="Min">
							<el-input v-model="ruleForm.Min" placeholder="最小值" clearable :disabled="ruleForm.Type!='date' && ruleForm.Type!='number'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="最大长度" prop="MaxLength">
							<el-input v-model="ruleForm.MaxLength" placeholder="最大长度" clearable :disabled="ruleForm.Type!='text' && ruleForm.Type!='textarea' && ruleForm.Type!='email'"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="多选" prop="Multiple">
						  <el-switch v-model="ruleForm.Multiple" active-text="是" inactive-text="否" active-value="1" inactive-value="0" class="ml-2" style="--el-switch-on-color: #13ce66;" :disabled="ruleForm.Type!='select'"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="设置值" prop="Value">
							<el-input v-model="ruleForm.Value" placeholder="设置值" clearable></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="isShowDialog = false"  >取 消</el-button>
					<el-button type="primary" @click="onSubmit(userForm)"  > 提交 </el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import { toRefs, reactive, onMounted, ref } from 'vue';
import { ElMessageBox, ElMessage, ElForm } from 'element-plus';
import Ztree from '/@/components/ztree/index.vue';
import { TreeAPI, SaveAPI, GetModelAPI, MoveToAPI, DelAPI, KeyExistAPI } from '/@/api/SystemConfigMenus/index';
import { useRouter } from 'vue-router';
import commonFunction from '/@/utils/commonFunction';
 
export default {
	name: '',
	components: {
		Ztree,
		 
	},
	setup() {
		const { copyText } = commonFunction();
		const ZtreeRef = ref();
		const router = useRouter();
		type FormInstance = InstanceType<typeof ElForm>;
		const userForm = ref<FormInstance>();
		const getZTree = (list, p) => {
			var carray = [];
			for (var i = 0; i < list.length; i++) {
				if (list[i]['ParentID'] === p) {
					
					var item = {};
					item['name'] = list[i]['Text'];
					item['id'] = list[i]['ID'];
					item['parent'] = p;
					var children = getZTree(list, item['id']);
					if (children && children.length > 0) {
						item['children'] = children;
					}
					carray.push(item);
				}
			}
				
			return carray;
		};

		const state: any = reactive({
			isShowDialog: false,
			TypeOptions: [{
			  "label": "单行文本框",
			  "value": 'text'
			}, {
			  "label": "多行文本框",
			  "value": 'textarea'
			}, {
			  "label": "单选按钮",
			  "value": 'radio'
			}, {
			  "label": "多选按钮",
			  "value": 'checkbox'
			}, {
			  "label": "下拉列表",
			  "value": 'select'
			}, {
			  "label": "日期",
			  "value": 'date'
			}, {
			  "label": "数字",
			  "value": 'number'
			}, {
			  "label": "电子邮件",
			  "value": 'email'
			}],
			HtmlOptions: [{
			  "label": "否",
			  "value": '0'
			}, {
			  "label": "是",
			  "value": '1'
			}],
			MultipleOptions: [{
			  "label": "否",
			  "value": '0'
			}, {
			  "label": "是",
			  "value": '1'
			}],
			ruleForm: {
				ID: 0,
				ParentID: 0,
				Key: '',
				Text: '',
				Value: '',
				Type: 'text',
				Html: '0',
				Multiple: null,
			},
			Lang: {},
			SelectID:'0',
		});
		const jsonData = reactive(state.Lang);
		
		// 页面加载时
		onMounted(() => {
			TreeInit(true);
		});
		
		/* 初始化树start */
		const TreeInit = (expandAll: boolean) => {
			TreeAPI({}).then(async (response) => {
				// console.log(response);
				if (response.code === 0) {
					let list = {};
					for (let i = 0; i < response.result.length; i++) {
						list[response.result[i].Key] = response.result[i].Text;
					}
					state.Lang = list;

					ZtreeRef.value.loadTree('系统配置', getZTree(response.result, '0'), setting);
						
					if (expandAll) {
						var zTree = ZtreeRef.value.getTreeObj();
						zTree.expandAll(true);
					}
				}
			});
		};
		/* 初始化树end */
		
		const setting = {
			edit: {
				enable: true,
				showRemoveBtn: false,
				showRenameBtn: false,
			},
			data: {
				simpleData: {
					enable: true,
					idKey: 'id',
					pIdKey: 'parent',
				},
			},
			callback: {
				onClick: function (event, treeId, treeNode) {
				 
				     var zTree = ZtreeRef.value.getTreeObj();
					 if(zTree.getSelectedNodes().length>0){
						 state.SelectID = zTree.getSelectedNodes()[0].id;
					 }
				},
				onDrag: function (event, treeId, treeNode) {
					//
				},
				onRename: function (event, treeId, treeNode, isCancel) {},
				onDrop: function (event, treeId, treeNodes, targetNode, moveType, isCopy) {
					let parentNode = treeNodes[0].getParentNode();
					let ParentID = parentNode == null ? '0' : parentNode.id;
					let ID = treeNodes[0].id;
					let Index = treeNodes[0].getIndex();
					let prams = {
						ID,
						ParentID,
						Index,
					};
					//console.log(prams);

					MoveToAPI(prams).then(async (response) => {
						//console.log(response);
						if (response['code'] === 0) {
							ElMessage.success(`${response.message}`);
							state.isShowDialog = false;
							TreeInit(true);
						}
					});
				},
			},
		};
		
		/* 打开编辑弹窗start */
		const onOpenEditMenu = () => {
			var zTree = ZtreeRef.value.getTreeObj();
			if (zTree.getSelectedNodes().length == 0) {
				ElMessageBox.alert('请点击选择一个节点以便编辑', '提示');
			} else {
				let ID = zTree.getSelectedNodes()[0].id;
				if (ID === '0') {
					ElMessageBox.alert('顶级菜单不能修改', '提示');
				} else {
					GetModelAPI({
						ID,
					}).then(async (response) => {
						if (response.code === 0) {
							state.ruleForm = response.result;
							state.isShowDialog = true;
						}
					});
				}
			}
		};
		 /* 打开编辑弹窗end */
		 
		 /* 打开新增弹窗start */
		const onOpenAddMenu = () => {
			var zTree = ZtreeRef.value.getTreeObj();
			state.ruleForm = {
				ID: 0,
				ParentID: zTree.getSelectedNodes().length > 0 ? zTree.getSelectedNodes()[0].id : '0',
				Key: '',
				Text: '',
				Value: '',
				Type: 'text',
				Html: '0',
				Multiple: null,
			};
			console.log(state.ruleForm)
			state.isShowDialog = true;
		};
		/* 打开新增弹窗end */
		
		/* 提交表单start */
		const onSubmit = (formEl: FormInstance | undefined) => {
			if (!formEl) return;
			formEl.validate((valid) => {
				if (valid) {
					SaveAPI(state.ruleForm).then(async (response) => {
						if (response['code'] === 0) {
							ElMessage.success(`${response.message}`);
							state.isShowDialog = false;
							TreeInit(false);
						}
					});
				} else {
					return false;
				}
			});
		};
		/* 提交表单end */
		
		/* 检查key是否存在start */
		const validateKey = (rule: any, value: any, callback: any) => {
			let prams = {
				Key: value,
				ID: state.ruleForm.ID,
			};
			KeyExistAPI(prams).then(async (response) => {
				//console.log(response);
				if (response.result) {
					callback(new Error(`${value} 这个KEY已经被占用`));
				} else {
					callback();
				}
			});
		};
		/* 检查key是否存在end */
		
		/* 复制ID start */
		const CopyID = () => {
			var zTree = ZtreeRef.value.getTreeObj();
			if (zTree.getSelectedNodes().length > 0) {
				let ID = zTree.getSelectedNodes()[0].id;
				copyText(ID);
			}
		};
		/* 复制ID end */
		
		/* 打开删除弹窗 start */
		const openDEL = () => {
			var zTree = ZtreeRef.value.getTreeObj();
			if (zTree.getSelectedNodes().length == 0) {
				ElMessageBox.alert('请点击选择一个节点以便操作', '提示');
			} else {
				let ID = zTree.getSelectedNodes()[0].id;
				if (ID === '0') {
					ElMessageBox.alert('顶级菜单不能删除', '提示');
				} else {
					ElMessageBox.confirm('删除后数据不可以恢复，是否继续?', '提醒', {
						confirmButtonText: '确定删除',
						cancelButtonText: '取 消',
						type: 'warning',
					})
						.then(() => {
							/*
						    ElMessage({
						      type: 'success',
						      message: '正在执行删除操作',
						    })
							*/
							DelAPI({
								ID,
							}).then(async (response) => {
								//console.log(response);
								if (response.code === 0) {
									ElMessage.success(`${response.message}`);

									TreeInit();
								}
							});
						})
						.catch(() => {
							ElMessage({
								type: 'info',
								message: '操作已取消',
							});
						});
				}
			}
		};
		/* 打开删除弹窗 end */
		
		const onOpenMenuURI = () => {
			var zTree = ZtreeRef.value.getTreeObj();
			if (zTree.getSelectedNodes().length == 0) {
				ElMessageBox.alert('请点击选择一个节点以便编辑', '提示');
			} else {
				let ID = zTree.getSelectedNodes()[0].id;
				if (ID === '0') {
					ElMessageBox.alert('顶级菜单不能操作', '提示');
				} else {
					router.push('/dev/usersmenu/menuuri/' + ID);
				}
			}
		};
		return {
			onOpenAddMenu,
			ZtreeRef,
			...toRefs(state),
			onSubmit,
			userForm,
			validateKey,
			onOpenEditMenu,
			openDEL,
			copyText,
			onOpenMenuURI,
			CopyID,
		 
		};
	},
};
</script>

<style scoped lang="scss">
.container {
}

.my-w-e-toolbar {
	text-align: right;
}

.tree-body {
	background-color: #fff;
	padding: 8px 10px;
}

.el-radio-group {
	display: block!important;
}
.el-radio {
	display: block!important;
}
</style>
